package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Quarantine;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.QuarantineVo;
import com.antdesignbackend.backend.service.QuarantineService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.*;

@RequestMapping("/quarantineInspection")
@Controller
public class QuarantineInspectionController extends BaseController {

    @Autowired
    QuarantineService quarantineService;

    @Autowired
    UserService userService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "quarantineInspection/index";
    }
    //待处理页面
    @GetMapping("/pending/index")
    @AuthToken
    public String PendingIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "pending/index";
    }
    //检疫记录页面
    @GetMapping("/quarantineRecord/index")
    @AuthToken
    public String QuarantineRecordIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "records/quarantineRecord/index";
    }
    /**
     * 分页查询
     * @param
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody QuarantineVo quarantineVo) {
        ReturnVO result = new ReturnVO();
        List<QuarantineVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<QuarantineVo> queryWrapper = new QueryWrapper<>();
            //判断用户权限
            Users users = userService.getById(getLoginUserId());
            if (users.getAuthType() == 1){ //地市权限
                queryWrapper.eq("cityCode",users.getAuthCity());
            }else if (users.getAuthType() == 2){ //区县权限
                queryWrapper.eq("districtCode",users.getAuthDistrict());
            }else if (users.getAuthType() == 3){
                queryWrapper.eq("townCode",users.getAuthTown());
            }else {
                return result;
            }
            //根据地市查询
            if(quarantineVo.getCityCode() != null && !quarantineVo.getCityCode().equals("-1")){
                queryWrapper.eq("cityCode",quarantineVo.getCityCode());
            }
            if(quarantineVo.getDistrictCode() != null && !quarantineVo.getDistrictCode().equals("-1")){
                queryWrapper.eq("districtCode",quarantineVo.getDistrictCode());
            }
            if(quarantineVo.getTownCode() != null && !quarantineVo.getTownCode().equals("-1")){
                queryWrapper.eq("townCode",quarantineVo.getTownCode());
            }
            if (quarantineVo.getApplicant() != null && !quarantineVo.getApplicant().equals(""))
                queryWrapper.like("applicant",quarantineVo.getApplicant());
            if (quarantineVo.getReportType() != null && !quarantineVo.getReportType().equals(""))
                queryWrapper.like("reportType",quarantineVo.getReportType());
            if (quarantineVo.getTimeInterval() != null && !quarantineVo.getTimeInterval().equals("")){
                String[] str=quarantineVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("reportDate",star,end);
            }if (quarantineVo.getState() != null && !quarantineVo.getState().equals("")){
                queryWrapper.eq("state",quarantineVo.getState());
            }
            queryWrapper.orderByDesc("reportDate");
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=quarantineService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist=quarantineService.search(queryWrapper,new Page<QuarantineVo>(quarantineVo.getPageIndex(),quarantineVo.getPageSize()));
                for(Quarantine quarantine:datalist){
                    quarantine.setLivestockPhoto(WebConfig.host+"images/"+quarantine.getLivestockPhoto());
                    quarantine.setCarPhoto(WebConfig.host+"images/"+quarantine.getCarPhoto());
                }
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 查询待处理
     * @param quarantineVo
     * @return
     */
    @PostMapping("/pending")
    @ResponseBody
    @AuthToken
    public ReturnVO pending(@RequestBody QuarantineVo quarantineVo) {
        ReturnVO result = new ReturnVO();
        List<Quarantine> datalist=new ArrayList<>();
        try {
            QueryWrapper<Quarantine> queryWrapper = new QueryWrapper<>();
            if (quarantineVo.getApplicant() != null && !quarantineVo.getApplicant().equals(""))
                queryWrapper.like("applicant",quarantineVo.getApplicant());
            if (quarantineVo.getReportType() != null && !quarantineVo.getReportType().equals(""))
                queryWrapper.like("reportType",quarantineVo.getReportType());
            if (quarantineVo.getTimeInterval() != null && !quarantineVo.getTimeInterval().equals("")){
                String[] str=quarantineVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("reportDate",star,end);
            }
            queryWrapper.orderByDesc("reportDate");
            queryWrapper.eq("state","0");
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=quarantineService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist=quarantineService.page(new Page<>(quarantineVo.getPageIndex(),quarantineVo.getPageSize()),queryWrapper).getRecords();
                for(Quarantine quarantine:datalist){
                    quarantine.setLivestockPhoto(WebConfig.host+"images/"+quarantine.getLivestockPhoto());
                    quarantine.setCarPhoto(WebConfig.host+"images/"+quarantine.getCarPhoto());
                }
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 查询所有已处理
     * @param quarantineVo
     * @return
     */
    @PostMapping("/quarantineRecord")
    @ResponseBody
    @AuthToken
    public ReturnVO quarantineRecord(@RequestBody QuarantineVo quarantineVo) {
        ReturnVO result = new ReturnVO();
        List<Quarantine> datalist=new ArrayList<>();
        try {
            QueryWrapper<Quarantine> queryWrapper = new QueryWrapper<>();
            if (quarantineVo.getApplicant() != null && !quarantineVo.getApplicant().equals(""))
                queryWrapper.like("applicant",quarantineVo.getApplicant());
            if (quarantineVo.getReportType() != null && !quarantineVo.getReportType().equals(""))
                queryWrapper.like("reportType",quarantineVo.getReportType());
            if (quarantineVo.getTimeInterval() != null && !quarantineVo.getTimeInterval().equals("")){
                String[] str=quarantineVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("reportDate",star,end);
            }
            queryWrapper.eq("state","1");
            queryWrapper.orderByDesc("reportDate");
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=quarantineService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist=quarantineService.page(new Page<>(quarantineVo.getPageIndex(),quarantineVo.getPageSize()),queryWrapper).getRecords();
                for(Quarantine quarantine:datalist){
                    quarantine.setLivestockPhoto(WebConfig.host+"images/"+quarantine.getLivestockPhoto());
                    quarantine.setCarPhoto(WebConfig.host+"images/"+quarantine.getCarPhoto());
                }
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody Quarantine quarantine) throws Exception {
        ReturnVO result = new ReturnVO();
        boolean b = false;
        if(quarantine.getQuarantineDate()!=null && !quarantine.getQuarantineDate().equals("")){
            if(quarantine.getQuarantineCode()!=null && !quarantine.getQuarantineCode().equals("")){
                quarantine.setState("1");
            }
        }
            b=quarantineService.updateById(quarantine);
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 删除
     * @param
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
        if (quarantineService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }

}
